<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

require_once('frontend.php');

class Users extends Frontend {

    function Users() {
        parent::__construct();
    }

    public function fomatDateForm($date) {
        if ($date != '') {
            $formatDate = preg_replace("![^0-9]+!i", '-', $date);
            $expdate = explode('-', $formatDate);
            $dateDatabase = $expdate[1] . '/' . $expdate[2] . '/' . $expdate[0];
            //$newDate = $dateDatabase->format('m-d-Y');
            return $dateDatabase;
        }
    }

    public function fomatDateDatabase($date) {
        if ($date != '') {
            $formatDate = preg_replace("![^0-9]+!i", '-', $date);
            $expdate = explode('-', $formatDate);
            $dateDatabase = new DateTime($expdate[2] . '-' . $expdate[0] . '-' . $expdate[1]);
            $newDate = $dateDatabase->format('Y-m-d');
            return $newDate;
        }
    }

    public function index($page = null, $action = null) {

        switch ($page) {
            case 'sign-in':
                $this->load->model('musers');
                $this->load->model('memployees');
                $this->load->helper('cookie');
                if ($action == 'submit') {
                    if ($this->input->post('email_address') != false && $this->input->post('password') != false) {
                        $email_address = $this->input->post('email_address');
                        $password = $this->input->post('password');
                        $res = $this->musers->getUserByEmail($email_address);
                        if ($res != null && $password != $this->user->decode_password($res['password'])) {
                            $user_right = $this->musers->checkUserRight($res['id']);
                            $user_info = $this->memployees->getEmployees($res['id']);
                            $this->session->set_userdata('user_right', $user_right);
                            $this->session->set_userdata('user_info', $user_info);
                            $key_cookie = random_string('alnum', 32);
                            if ($this->input->post('remember_me') != FALSE) {
                                $decode_username = md5('username');
                                $c_username = array(
                                    'name' => $decode_username,
                                    'value' => $this->user->encode_password($res['username']),
                                    'expire' => 604800, //1 week
                                    'secure' => FALSE
                                );
                                $this->input->set_cookie($c_username);
                                $decode_password = md5('password');
                                $c_password = array(
                                    'name' => $decode_password,
                                    'value' => md5($res['password']),
                                    'expire' => 604800, //1 week
                                    'secure' => FALSE
                                );
                                $this->input->set_cookie($c_password);
                                $decode_key_cookie = md5('key_cookie');
                                $c_key_cookie = array(
                                    'name' => $decode_key_cookie,
                                    'value' => $key_cookie,
                                    'expire' => 604800, //1 week
                                    'secure' => FALSE
                                );
                                $this->input->set_cookie($c_key_cookie);
                            }
                            $data = array(
                                'key_cookie' => $key_cookie
                            );
                            $this->musers->updateUser($data, $res['id']);
                            redirect('my-dashboard');
                        } else {
                            $this->resetSessionAcc();
                            redirect();
                        }
                    } else {
                        $this->resetSessionAcc();
                        redirect();
                    }
                } else {
                    $this->resetSessionAcc();
                    redirect();
                }
                break;
            case 'sign-out':
                $this->load->helper('cookie');
                if ($this->input->cookie(md5('username')) != FALSE) {
                    delete_cookie(md5('username'));
                    delete_cookie(md5('password'));
                    delete_cookie(md5('key_cookie'));
                }
                $this->resetSessionAcc();
                redirect();
                break;
            case 'lost-password':
                if ($action == 'submit') {
                    $email = $this->input->post('email_address');
                    $this->lostpassword($email);
                } else {
                    $this->layout[AppContants::LAYOUT_CSS] = array('style-login');
                    //Default js
                    $this->layout[AppContants::LAYOUT_JS] = array();
                    if ($this->session->userdata('send_lost_password') != FALSE) {
                        $this->layout[AppContants::LAYOUT_STEPVIEW] = "users/lost-finish";
                        $this->session->unset_userdata('send_lost_password');
                    } else {
                        $this->layout[AppContants::LAYOUT_STEPVIEW] = "users/lost-password";
                    }
                    $this->data['templatelogin'] = 'login';
                }
                break;
            case 'recovery-password':
                $this->load->model('musers');
                $this->load->model('memployees');
                $this->load->helper(array('date'));
                $this->load->library(array('emailer', 'parser'));
                $this->lang->load('account');

                $this->layout[AppContants::LAYOUT_CSS] = array('style-login');
                if ($action == 'submit') {
                    if ($this->session->userdata('userId') != FALSE) {
                        $userId = $this->session->userdata('userId');
                        $username = $this->session->userdata('username_user');
                        $active_code = random_string('alnum', 32);
                        if ($this->input->post('password') != FALSE) {
                            $password = $this->input->post('password');
                            $encodePassword = $this->user->encode_password($password);

                            $user_right = $this->musers->checkUserRight($userId);
                            $user_info = $this->memployees->getEmployees($userId);
                            if ($user_info != null && $user_right != null) {
                                $this->session->set_userdata('user_right', $user_right);
                                $this->session->set_userdata('user_info', $user_info);
                                $data = array(
                                    'password' => $encodePassword,
                                    'send_welcome_email' => 'yes',
                                    'key_activate' => $active_code,
                                    'updated_by' => $userId,
                                    'updated_date' => getDateTime()
                                );
                                $this->musers->updateUser($data, $userId);
                            }

                            //send mail
                            $infor['password'] = $password;
                            $message = $this->parser->parse('../../htdocs/email_templates/change_password', $infor, TRUE);
                            $subject = $this->lang->line('CHANGE_PASSWORD');
                            $this->emailer->send_email('email_from', $username, $subject, $message, '', 'thomar@php-vn.com', '');

                            $this->session->unset_userdata('username_user');
                            $this->session->unset_userdata('userId');
                            $this->session->unset_userdata('key_activate');
                            redirect('my-dashboard');
                        }
                    }
                }
                $this->layout[AppContants::LAYOUT_STEPVIEW] = "users/recoverypassword";
                $this->data['templatelogin'] = 'login';
                break;
            default:
                break;
        }
    }

    /**
     * Description: Reset Session
     */
    public function resetSessionAcc() {
        $newdata = array(
            'session_id' => $this->session->userdata('session_id'),
            'ip_address' => $this->session->userdata('ip_address'),
            'user_agent' => $this->session->userdata('user_agent'),
            'last_activity' => $this->session->userdata('last_activity'),
            'user_data' => $this->session->userdata('user_data'));

        foreach (array_keys($this->session->userdata) as $key) {
            $this->session->unset_userdata($key);
        }
        session_destroy();
        $this->session->set_userdata($newdata);
    }

    /**
     * Description: General a link to change password for customer
     * @param string $email
     */
    public function lostpassword($email) {
        $this->load->model('musers');
        $this->load->library(array('emailer', 'parser'));
        $this->load->helper('date');
        $this->lang->load('account');

        $res = null;

        //check email in table users
        $res = $this->musers->getUserByEmail($email);
        if ($res != null) {
            $active_code = random_string('alnum', 32);
            $updated_date = getDateTime();
            $data = array(
                'key_activate' => $active_code,
                'updated_date' => $updated_date
            );
            $update_res = $this->musers->updateUser($data, $res['id'], AppContants::ACTIVE_STATUS);
            if ($update_res == TRUE) {
                $base_url['url'] = "<br/>" . base_url("recoverypass/{$res['id']}/" . $active_code);
                $message = $this->parser->parse('../../htdocs/email_templates/lost-password', $base_url, TRUE);
                $subject = $this->lang->line('LOST_PASSWORD');
                $sent = $this->emailer->send_email('email_from', $res['username'], $subject, $message, '', 'thomar@php-vn.com', '');

                if ($sent == TRUE) {
                    $this->session->set_userdata('send_lost_password', 'send');
                    redirect('lost-password');
                }
            }
        } else {
            $this->layout[AppContants::LAYOUT_MESSAGE_ACCOUNT] = "<script language=\"javascript\">
                                                                alert('The email address: $email is not already on Human Resource Management')
                                                                </script>";
            $this->layout[AppContants::LAYOUT_CSS] = array('style-login');
            //Default js
            $this->layout[AppContants::LAYOUT_JS] = array();
            $this->layout[AppContants::LAYOUT_STEPVIEW] = "users/lost-password";
            $this->data['templatelogin'] = 'login';
        }
    }

    /**
     * Description: Change password form recovery link
     * @param int $useID
     * @param string $active_code
     */
    public function recoverypass($useID, $active_code) {
        $this->load->model('musers');

        $account_res = $this->musers->getUsersByUserIdActivecode($useID, $active_code);
        if ($account_res != null) {
            $data1 = array();
            $data1['username_user'] = $account_res['username'];
            $data1['userId'] = $useID;
            $data1['key_activate'] = $active_code;
            $this->session->set_userdata($data1);
            redirect("recovery-password");
        } else {
            redirect("lost_failed");
        }
    }

}
